
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Test01Serve
 */
public class Test01Server {

  public static void main(String[] args) throws Exception {
    // 创建ServerSocket供客户端连接 - 端口要和客户端保持一致
    ServerSocket serverSocket = new ServerSocket(8989);
    System.out.println("服务器端启动成功，端口是8989");
    // 接收客户端的请求
    Socket socket = serverSocket.accept();
    System.out.println("客户端连接成功" + socket);
    // 获取IO流对象
    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    // 数据传输
    byte[] bytes = new byte[1024];
    int len = is.read(bytes);
    System.out.println("服务器端读取客户端数据成功");
    System.out.println("客户端发来的数据：" + new String(bytes, 0, len));
    // 返回一条数据给客户端
    os.write("hello world,我是服务器".getBytes());
    System.out.println("数据发送完毕");
    // 关闭资源
    os.close();
    is.close();
    socket.close();
    serverSocket.close();
  }
}